import { useEffect, useMemo, useRef, useState } from "react";
import { listConfig, delConfig, exportConfig, getInitData, addConfig, updateConfig } from '@/api/system/pageConfig'

import SearchForm from "../../../components/searchForm";
import { Table, Flex, Button, Divider, message, Modal } from "antd";
import { ModalForm } from "@ant-design/pro-components";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { useDictionary } from "@/hooks";
import DisplayLabel from "@/components/displayLabel";
import { Link, useNavigate } from "react-router-dom";
import ConfigForm from "./modules/ConfigForm";

const queryItems = [
  {
    name: 'name',
    label: '页面名称',
    type: 'INPUT',
  }
];
//i18n
const AppMenuIndex = () => {
  useDictionary(['SYS_APP_TYPE']);
  const [queryParam, setQueryParam] = useState({});
  const [page, setPage] = useState({ pageNo: 1, pageSize: 10 });
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const columns = [
    {
      title: '页面名称',
      dataIndex: 'name'
    },
    {
      title: '页面描述',
      dataIndex: 'remark'
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime'
    },
    {
      title: '操作',
      key: 'action',
      width: '200',
      render: (_, record) => (
        <>
          <Link to={`/integration/org/pageConfigDetail?id=${record.id}&name=${record.name}&appId=${record.appId}`}>设计</Link>
          <Divider type="vertical" />
          <a onClick={() => { }}>访问地址</a>
          <Divider type="vertical" />
          <Link to={`/integration/org/pageConfigDetail?id=${record.id}&name=${record.name}&appId=${record.appId}`}>集成调试</Link>
          <Divider type="vertical" />
          <a onClick={() => { deleteConfirm(record) }}>删除</a>
        </>
      ),
    },
  ];

  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['page-config-list', queryParam, page],
    queryFn: () => {
      return listConfig({
        pageNum: page.pageNo,
        pageSize: page.pageSize,
        ...queryParam
      }).then((res) => {
        return res.data || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
  })
  
  const saveData = (values) => {
    if (values.id) {
      return updateConfig(values).then((res) => {
        if (res.code !== 200) return;
        refetch()
        message.success('修改成功')
        return true
      })
    } else {
      return addConfig(values).then((res) => {
        if (res.code !== 200) return;
        refetch()
        message.success('新增成功')
        return true
      })
    }
  }
  const confirm = Modal.confirm;
  
  const deleteConfirm = (row) => {
    const ids = row.id || selectedRowKeys
    confirm({
      title: '确认删除所选中数据?',
      autoFocusButton: null,
      onOk() {
        return delConfig(ids)
          .then(() => {
            onSelectChange([], [])
            refetch()
            message.success('删除成功')
          })
      },
      onCancel() { },
    });
  };
  
  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }

  return (
    <Flex vertical={true} className="searchTableWrapper">
      <div className="searchTableHeader">页面配置</div>
      <SearchForm
        onSearch={(values) => {
          if (JSON.stringify(values) !== JSON.stringify(queryParam)) {
            setQueryParam({ ...values })
          } else {
            refetch()
          }
        }}
        items={queryItems}
        searchContent="查询"
        buttons={<>
          <ModalForm
            trigger={<Button type="primary">新增</Button>}
            title="添加应用管理"
            modalProps={{ destroyOnClose: true }}
            onFinish={saveData}
            grid={true}
          >
            <ConfigForm />
          </ModalForm>
          {selectedRowKeys.length > 0 && <Button className="ml-2" danger onClick={deleteConfirm}>批量删除</Button>}
        </>}
      />
      <Table
        rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
        columns={columns}
        rowKey={(record) => record.id}
        loading={isFetching}
        dataSource={tableData?.list}
        pagination={{
          current: page.pageNo,
          pageSize: page.pageSize,
          total: tableData?.total,
          onChange: (pageNo, pageSize) => {
            setPage({ pageNo, pageSize })
          }
        }}
      />
    </Flex >
  );
};


export default AppMenuIndex;
